﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Org.Vesic.WinForms;
using System.Net.Mail;

namespace TimeControllerApp
{



    public partial class MaxForm : Form
    {
        timeMode[] outmodes = new timeMode[5];
        timeMode[] inmodes = new timeMode[5];
        ActionButton[] actionbuttons;
        timeMode nonspecial;
        FormState formState = new FormState();

        public int actionid;
        public int statusid;
        public int userid;

        DateTime dt0000AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 0);
        DateTime dt0700AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 07, 0, 0);
        DateTime dt0900PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 09, 0, 0);
        DateTime dt1000PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 00, 0);
        DateTime dt1230PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 30, 0);
        DateTime dt1330PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 13, 30, 0);
        DateTime dt1500PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 15, 0, 0);
        DateTime dt1600PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 16, 0, 0);

        public void showspecialbuttons(bool show, int exceptid = -1)
        {
            if (actionbuttons != null)
            {
                foreach (ActionButton a in actionbuttons)
                {
                    if (show == true) a.Visible = show;
                    else if (a.actionid != exceptid)
                    {
                        this.Controls.Remove(a);
                        a.Dispose();
                    }
                }
            }
        }

        public MaxForm()
        {
            InitializeComponent();
            formState.Maximize(this);
            barcodebox.Focus();
            Console.Write("");
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            Cursor.Hide();
            labelShowTime.Text = "";
            timer1.Start();
            ResetButtons();
        }

        private void ResetButtons()
        {
            textBoxNameSurname.Text = "";
            textBoxCodeNumber.Text = "";
            textBoxEntranceHour.Text = "";
            textBoxLastStatus.Text = "";
            buttonIn.Visible = true;
            buttonOut.Visible = true;
            buttonInMorning.Visible = false;
            buttonInSpecial.Visible = false;
            buttonOutLunch.Visible = false;
            buttonOutSpecial.Visible = false;
            buttonApprove.Visible = false;
            buttonIn.Enabled = false;
            buttonOut.Enabled = false;
            buttonInMorning.Enabled = true;
            buttonInSpecial.Enabled = true;
            buttonOutLunch.Enabled = true;
            buttonOutSpecial.Enabled = true;
            showspecialbuttons(false);
        }   

        private void createbuttons(String mode)
        {
            int now = DateTime.Now.Hour * 60 + DateTime.Now.Minute;
            String query;

            if (mode == "in") query = "Select * From dbo.Actions Where StatusID = 1 And StartTime < " + now + " AND EndTime>" + now;
            else query = "Select * From dbo.Actions Where StatusID != 1 And StartTime < " + now + " AND EndTime>" + now;

            DataSet dsinmodes = DB.Sorgula(query, "");
            inmodes = new timeMode[dsinmodes.Tables[0].Rows.Count];
            int i = 0;
            foreach (DataRow row in dsinmodes.Tables[0].Rows)
            {

                inmodes[i] = new timeMode((int)row["ActionID"], (int)row["StatusID"], row["Title"].ToString(), (int)row["Special"]);
                i++;
            }

            int specialcount = 0;
            foreach (timeMode tm in inmodes)
            {
                if (tm.special == 0)
                {
                    buttonInMorning.Text = tm.title;
                    nonspecial = tm;
                }
                else
                {
                    specialcount++;
                }
            }

            actionbuttons = new ActionButton[specialcount];
            int k = 0;
            foreach (timeMode tm in inmodes)
            {
                if (tm.special == 1)
                {
                    actionbuttons[k] = new ActionButton(this, tm.id, tm.status, (176 + (208 / specialcount) * k), (208 / specialcount) - 1, tm.title);
                    k++;
                }
            }

        }

        private void buttonIn_Click(object sender, EventArgs e)
        {
            createbuttons("in");
            buttonIn.Visible = true;
            buttonOut.Visible = false;
            buttonInMorning.Visible = true;
            buttonInSpecial.Visible = true;
            buttonOutLunch.Visible = false;
            buttonOutSpecial.Visible = false;
            buttonIn.Enabled = false;
            refreshDateTimes(dt0000AM, dt0700AM, dt0900PM, dt1000PM, dt1230PM, dt1330PM, dt1500PM, dt1600PM);

            if (DateTime.Now.TimeOfDay.Ticks > dt0700AM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1230PM.TimeOfDay.Ticks)
            {
                buttonInMorning.Visible = true;
                buttonInMorning.Text = "Mañana";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1230PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1330PM.TimeOfDay.Ticks)
            {
                buttonInMorning.Visible = true;
                buttonInMorning.Text = "Mañana";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1330PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1500PM.TimeOfDay.Ticks)
            {
                buttonInMorning.Visible = true;
                buttonInMorning.Text = "Comida";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1500PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1600PM.TimeOfDay.Ticks)
            {
                buttonInMorning.Visible = true;
                buttonInMorning.Text = "Comida";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1600PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt0000AM.TimeOfDay.Ticks)
            {
                buttonInMorning.Visible = false;
                buttonInMorning.Text = "Salida";
            }

        }

        private void buttonInMorning_Click(object sender, EventArgs e)
        {

            refreshDateTimes(dt0000AM, dt0700AM, dt0900PM, dt1000PM, dt1230PM, dt1330PM, dt1500PM, dt1600PM);

            if (DateTime.Now.TimeOfDay.Ticks > dt0700AM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1330PM.TimeOfDay.Ticks)
            {
                actionid = 1;
                statusid = 1;
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1330PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1600PM.TimeOfDay.Ticks)
            {
                actionid = 6;
                statusid = 1;
            }

            buttonIn.Visible = true;
            buttonOut.Visible = false;
            buttonInMorning.Visible = true;
            buttonInSpecial.Visible = false;
            buttonOutLunch.Visible = false;
            buttonOutSpecial.Visible = false;
            buttonApprove.Visible = true;
            buttonIn.Enabled = false;
            showspecialbuttons(false);
            buttonInMorning.Enabled = false;
        }

        private void buttonInSpecial_Click(object sender, EventArgs e)
        {
            foreach (ActionButton a in actionbuttons)
            {
                a.Visible = true;
            }
            buttonIn.Visible = true;
            buttonOut.Visible = false;
            buttonInMorning.Visible = false;
            buttonInSpecial.Visible = true;
            buttonOutLunch.Visible = false;
            buttonOutSpecial.Visible = false;
            showspecialbuttons(true);
            buttonIn.Enabled = false;
            buttonInSpecial.Enabled = false;
        }

        private void buttonOut_Click(object sender, EventArgs e)
        {
            createbuttons("out");
            buttonIn.Visible = false;
            buttonOut.Visible = true;
            buttonInMorning.Visible = false;
            buttonInSpecial.Visible = false;
            buttonOutLunch.Visible = true;
            buttonOutSpecial.Visible = true;
            buttonOut.Enabled = false;
            refreshDateTimes(dt0000AM, dt0700AM, dt0900PM, dt1000PM, dt1230PM, dt1330PM, dt1500PM, dt1600PM);

            if (DateTime.Now.TimeOfDay.Ticks > dt0700AM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1230PM.TimeOfDay.Ticks)
            {
                buttonOutLunch.Visible = false;
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1230PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1330PM.TimeOfDay.Ticks)
            {
                buttonOutLunch.Visible = true;
                buttonOutLunch.Text = "Comida";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1330PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1500PM.TimeOfDay.Ticks)
            {
                buttonOutLunch.Visible = true;
                buttonOutLunch.Text = "Comida";
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1500PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1600PM.TimeOfDay.Ticks)
            {
                buttonOutLunch.Visible = false;
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1600PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt0000AM.TimeOfDay.Ticks)
            {
                buttonOutLunch.Visible = true;
                buttonOutLunch.Text = "Salida";
            }
        }

        private void buttonOutLunch_Click(object sender, EventArgs e)
        {
            refreshDateTimes(dt0000AM, dt0700AM, dt0900PM, dt1000PM, dt1230PM, dt1330PM, dt1500PM, dt1600PM);

            if (DateTime.Now.TimeOfDay.Ticks > dt1230PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt1500PM.TimeOfDay.Ticks)
            {
                actionid = 7;
                statusid = 6;
            }

            if (DateTime.Now.TimeOfDay.Ticks > dt1600PM.TimeOfDay.Ticks && DateTime.Now.TimeOfDay.Ticks < dt0000AM.TimeOfDay.Ticks)
            {
                actionid = 12;
                statusid = 2;
            }


            buttonIn.Visible = false;
            buttonOut.Visible = true;
            buttonInMorning.Visible = false;
            buttonInSpecial.Visible = false;
            buttonOutLunch.Visible = true;
            buttonOutSpecial.Visible = false;
            buttonApprove.Visible = true;
            buttonOut.Enabled = false;
            buttonOutLunch.Enabled = false;
        }

        private void buttonApprove_Click(object sender, EventArgs e)
        {
            refreshDateTimes(dt0000AM, dt0700AM, dt0900PM, dt1000PM, dt1230PM, dt1330PM, dt1500PM, dt1600PM);
            String employeeName = "";
            String mailAddressOfSupervisor = "";
            int userIdOfSuperVisor;

            bool useraction = DB.Uygula("INSERT INTO dbo.EmployeeActions (EmployeeID,ActionID,ActionTime) VALUES (" + userid + "," + actionid + ",GETDATE())", "");

            String time = DateTime.Now.ToString();

            if (useraction == true)
            {
                bool userinfo = DB.Uygula("UPDATE dbo.Employees SET StatusID =" + statusid + " WHERE EmployeeID = " + userid, "");
            }

            try
            {
                //saat 9-10 arası ise veya 15-16 arası ise, ve user action in from lunch veya in morning ise
                if (((DateTime.Now.TimeOfDay.Ticks > dt1500PM.TimeOfDay.Ticks && 
                      DateTime.Now.TimeOfDay.Ticks < dt1600PM.TimeOfDay.Ticks && useraction == true) ||
                     (DateTime.Now.TimeOfDay.Ticks > dt0900PM.TimeOfDay.Ticks &&
                      DateTime.Now.TimeOfDay.Ticks < dt1000PM.TimeOfDay.Ticks && useraction == true)) &&
                    (actionid == 1 || actionid == 6))
                {

                    DataSet dsuser = DB.Sorgula("SELECT * FROM dbo.Employees WHERE EmployeeID = '" + userid + "';", "");
                    if (dsuser != null || dsuser.Tables.Count > 0)
                    {
                        //geç kalan elemanın adı ve supervisor userid si
                        employeeName = dsuser.Tables[0].Rows[0]["NameSurname"].ToString();
                        userIdOfSuperVisor = (int)dsuser.Tables[0].Rows[0]["ManagerID"];

                        DataSet dsMail = DB.Sorgula("SELECT * FROM dbo.Employees WHERE EmployeeID = '" + userIdOfSuperVisor + "';", "");
                        if (dsMail != null || dsuser.Tables.Count > 0)
                        {
                            //supervisor un mail adresi
                            mailAddressOfSupervisor = dsMail.Tables[0].Rows[0]["EMail"].ToString();
                        }

                        SendMail(employeeName, mailAddressOfSupervisor, time, actionid);
                    }
                }
            }

            catch (Exception ex)
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("192.168.100.25");

                mail.From = new MailAddress("admin@eclipsenet.com");
                mail.To.Add("ionur@eclipsenet.com");
                mail.Subject = "System Error";
                mail.Body = "Theres an error in the system " + ex.Message;

                SmtpServer.Port = 25;
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }

            ResetButtons();
        }


        private void MaxForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                DateTime dtDbSorgula = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                string date = dtDbSorgula.Year+"-"+dtDbSorgula.Month+"-"+dtDbSorgula.Day+" 00:00:00.000";

                string lastMovements = "";

                String code = barcodebox.Text.Trim();
                
                DataSet dsLastMovement = DB.Sorgula(@"SELECT TOP 10 emp.EmployeeID,
                                                            emp.NameSurname, 
                                                            emp.Code, 
                                                            ea.ActionTime, 
                                                            ac.Title + case ac.StatusID
                                                                            when 1 then ' - Entrada'
                                                                            when 2 then ' - Salida'
                                                                            when 6 then ' - Salida'
                                                                            when 3 then ' - Salida'
                                                                            when 5 then ' - Salida'
                                                                            when 4 then ' - Salida'
                                                                            when 8 then ' - Salida'
                                                                            end as 'last_movement'
                                                       FROM dbo.Employees emp, 
	                                                        dbo.EmployeeActions ea, 
	                                                        dbo.Actions ac
                                                      WHERE emp.Code= '" + code + "'  AND ea.ActionTime > '"+ date + "' AND emp.EmployeeID=ea.EmployeeID AND ea.ActionID=ac.ActionID ORDER BY ea.ActionTime desc", "");


                DataSet dsUserInfo = DB.Sorgula(@"SELECT emp.EmployeeID,
                                                      emp.NameSurname, 
                                                      emp.Code
                                                 FROM dbo.Employees emp
                                                WHERE emp.Code= '" + code + "' ", "");

                                                     
                barcodebox.Text = "";
                if ((dsLastMovement != null || dsLastMovement.Tables.Count > 0) && 
                    (dsUserInfo != null || dsUserInfo.Tables.Count > 0))
                {
                    userid = (int)dsUserInfo.Tables[0].Rows[0]["EmployeeID"];
                    textBoxNameSurname.Text = dsUserInfo.Tables[0].Rows[0]["NameSurname"].ToString();
                    textBoxCodeNumber.Text = dsUserInfo.Tables[0].Rows[0]["Code"].ToString();

                    foreach (DataRow row in dsLastMovement.Tables[0].Rows)
                    {
                        lastMovements += row["last_movement"].ToString()+Environment.NewLine;
                    }

                    textBoxLastStatus.Text = lastMovements;

                    textBoxEntranceHour.Text = DateTime.Now.ToShortDateString()+" / "+DateTime.Now.ToShortTimeString();
                    
                    buttonIn.Enabled = true;
                    buttonOut.Enabled = true;
                }
            }
        }

        private void SendMail(String employeeName, String mailAddressOfSupervisor, String time, int actionId)
        {
            string mod = "";

            if (actionid == 1)
            {
                mod = "han llegado tarde pasadas las 09:00 AM";
            }
            else if (actionid == 6)
            {
                mod = "han llegado tarde pasadas las 15:00 PM";
            }

            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("192.168.100.25");

                mail.From = new MailAddress("admin@eclipsenet.com");
                mail.To.Add(mailAddressOfSupervisor);
                mail.CC.Add("aescobar@eclipsenet.com");
                mail.Subject = "Personas que han llegado tarde";
                mail.Body = employeeName + " " + mod + Environment.NewLine + "( Hora de entrada : " +time + " )";

                SmtpServer.Port = 25;
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void sendMailForMissingEmployees()
        {
            DataSet dsuser = DB.Sorgula("SELECT NameSurname, StatusName FROM dbo.Employees, dbo.Status where Employees.StatusID in(2,3,4,5,6,8) and Employees.StatusID=Status.StatusID order by Employees.NameSurname asc ", "");

            string mailBody = "Las siguientes personas no estan hoy en la empresa: \n";

            if (dsuser != null || dsuser.Tables.Count > 0)
            {
                foreach (DataRow row in dsuser.Tables[0].Rows)
                {
                    mailBody = mailBody +"\n" + "Nombre y Apellidos : " + row["NameSurname"].ToString() +  ". ";
                }
            }

            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("192.168.100.25");

                mail.From = new MailAddress("admin@eclipsenet.com");
                mail.To.Add("aescobar@eclipsenet.com");
                mail.Bcc.Add("ionur@eclipsenet.com");
                mail.Subject = "Personas que no han venido hoy";
                mail.Body = mailBody;

                SmtpServer.Port = 25;
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }

            catch (Exception ex)
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("192.168.100.25");

                mail.From = new MailAddress("admin@eclipsenet.com");
                mail.To.Add("ionur@eclipsenet.com");
                mail.Subject = "System Error";
                mail.Body = "Theres an error in the system " + ex.Message;

                SmtpServer.Port = 25;
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
        }



        private void buttonCancel_Click(object sender, EventArgs e)
        {
            ResetButtons();
        }

        private void buttonOutSpecial_Click(object sender, EventArgs e)
        {
            buttonIn.Visible = false;
            buttonOut.Visible = true;
            buttonInMorning.Visible = false;
            buttonInSpecial.Visible = false;
            buttonOutLunch.Visible = false;
            buttonOutSpecial.Visible = true;
            showspecialbuttons(true);
            buttonOut.Enabled = false;
            buttonOutSpecial.Enabled = false;

        }

        private void buttonCustomerVendor_Click(object sender, EventArgs e)
        {
            buttonApprove.Visible = true;
        }

        private void buttonPersonal_Click(object sender, EventArgs e)
        {
            buttonApprove.Visible = true;
        }

        private void buttonSpecialDoctor_Click(object sender, EventArgs e)
        {
            buttonApprove.Visible = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labelShowTime.Text = System.DateTime.Now.ToLongTimeString();

            if (DateTime.Now.TimeOfDay.Hours == 10 && 
                DateTime.Now.TimeOfDay.Minutes == 9 && 
                DateTime.Now.TimeOfDay.Seconds == 25)
            {
                sendMailForMissingEmployees();
            }
        }

        private void buttonGeneralDoctor_Click(object sender, EventArgs e)
        {
            buttonApprove.Visible = true;
        }

        private void barcodebox_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void buttonApprove_Click_1(object sender, EventArgs e)
        {
            barcodebox.Focus();

        }

        private void MaxForm_Shown(object sender, EventArgs e)
        {
            barcodebox.Focus();
        }

        private void barcodebox_Leave(object sender, EventArgs e)
        {
            barcodebox.Focus();
        }

        private void refreshDateTimes(DateTime dt0000AM, DateTime dt0700AM, DateTime dt0900PM,
                                      DateTime dt1000PM, DateTime dt1230PM, DateTime dt1330PM,
                                      DateTime dt1500PM, DateTime dt1600PM)
        {
            dt0000AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 01, 0);
            dt0700AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 07, 0, 0);
            dt0900PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 09, 0, 0);
            dt1000PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 00, 0);
            dt1230PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 30, 0);
            dt1330PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 13, 30, 0);
            dt1500PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 15, 0, 0);
            dt1600PM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 16, 0, 0);
        }
    }

    class timeMode
    {
        public int id;
        public int status;
        public String title;
        public int special;

        public timeMode(int id, int status, String name, int special)
        {
            this.id = id;
            this.status = status;
            this.title = name;
            this.special = special;
        }
    }

    class ActionButton : Button
    {
        public int actionid;
        public int statusid;
        MaxForm form;
        public ActionButton(MaxForm frm, int actionid, int statusid, int y, int height, String title)
            : base()
        {
            this.form = frm;
            this.actionid = actionid;
            this.statusid = statusid;
            this.BackColor = System.Drawing.Color.SteelBlue;
            this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
            this.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.Location = new System.Drawing.Point(370, y);
            this.Size = new System.Drawing.Size(198, height);
            this.Text = title;
            this.UseVisualStyleBackColor = false;
            this.Click += new System.EventHandler(this.buttonClick);
            this.Visible = false;
            frm.groupBoxInOut.Controls.Add(this);
        }

        private void buttonClick(object sender, EventArgs e)
        {
            form.actionid = this.actionid;
            form.statusid = this.statusid;
            form.buttonApprove.Visible = true;
            form.showspecialbuttons(false, this.actionid);
        }
    }

}
